package com.wlyy.his.ze.hepler;


import com.wlyy.his.ze.bean.base.BASEINFO;
import com.wlyy.his.ze.bean.request.GUAHAOKSXX_IN_request;
import com.wlyy.his.ze.bean.response.GUAHAOKSXX_OUT;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.*;

@SuppressWarnings("unchecked")
public class HttpClientUtilsZEDemo {
    private static PoolingHttpClientConnectionManager secureConnectionManager;
    private static HttpClientBuilder secureHttpBulder = null;
    private static RequestConfig requestConfig = null;
    private static int MAXCONNECTION = 10;
    private static int DEFAULTMAXCONNECTION = 5;

    //证书地址
    private static final String CLIENT_KEY_STORE = "C:\\Users\\10097\\Desktop\\client.keystore.jks";
    private static final String CLIENT_TRUST_KEY_STORE = "C:\\Users\\10097\\Desktop\\client.keystore.jks";


    private static String CLIENT_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_KEY_PASS = "123456";

	/**
     * 进行安全通信的主机和端口
     */

    private static String HOST = "183.129.242.246";
    private static int PORT = 19081;




    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(60000)
                .setConnectTimeout(60000)
                .setConnectionRequestTimeout(120000)
                .build();

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream trustStoreInput = new FileInputStream(new File(CLIENT_TRUST_KEY_STORE));
            trustStore.load(trustStoreInput, CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
            KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream clientKeyStoreInput = new FileInputStream(new File(CLIENT_KEY_STORE));
            clientKeyStore.load(clientKeyStoreInput, CLIENT_KEY_STORE_PASSWORD.toCharArray());

            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(clientKeyStore, CLIENT_KEY_PASS.toCharArray())
                    .setSecureRandom(new SecureRandom())
                    .useSSL()
                    .build();

            ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
            SSLConnectionSocketFactory sslSocketFactoy = new SSLConnectionSocketFactory(
                    sslContext, new String[]{"SSLv3"}, null,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    //.register("http", plainSocketFactory)
                    .register("https", sslSocketFactoy)
                    .build();

            secureConnectionManager = new PoolingHttpClientConnectionManager(r);
            HttpHost target = new HttpHost(HOST, PORT, "https");
            secureConnectionManager.setMaxTotal(MAXCONNECTION);
            //设置每个Route的连接最大数
            secureConnectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);
            //设置指定域的连接最大数
            secureConnectionManager.setMaxPerRoute(new HttpRoute(target), 20);
            secureHttpBulder = HttpClients.custom()
                    .setConnectionManager(secureConnectionManager)
                    .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }
    }
    
    
    public static void main(String args[]) throws Exception {

    	Map<String, String> map = RENYUANMXCX();

		for(int i=0;i<1;i++){
			MyThread myThread1 = new MyThread("RENYUANMXCX()",map);
			myThread1.start();
		}
    }

    public static CloseableHttpClient getSecureConnection() throws Exception {
        return secureHttpBulder.build();
    }

    public static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            params.add(pair);
        }
        HttpUriRequest reqMethod = null;
        if ("post".equals(method)) {
            reqMethod = RequestBuilder.post().setUri(url)
                    .addParameters(params.toArray(new NameValuePair[0]))
                    .setConfig(requestConfig).build();
        } else if ("get".equals(method)) {
            reqMethod = RequestBuilder.get().setUri(url)
                    .addParameters(params.toArray(new NameValuePair[0]))
                    .setConfig(requestConfig).build();
        }
        return reqMethod;
    }

   
 
    public static Map<String, String> RENYUANMXCX(){

        GUAHAOKSXX_IN_request requestGUAHAOKSXX_IN= new GUAHAOKSXX_IN_request();
        BASEINFO info = new BASEINFO();
        //info.setCAOZUORQ("2021-08-27");
        info.setCAOZUOYDM("APP");
        info.setCAOZUOYXM("APP");
        //info.setFENYUANDM("5");
        //info.setZHONGDUAJBH("330103600131");
        //info.setZHONGDUANLSH("33010360013120170316074209632");

        requestGUAHAOKSXX_IN.setBASEINFO(info);
        requestGUAHAOKSXX_IN.setGUAHAOBC("0");
        requestGUAHAOKSXX_IN.setGUAHAOFS("2");
        requestGUAHAOKSXX_IN.setGUAHAOLB("1");
        requestGUAHAOKSXX_IN.setRIQI("");
        requestGUAHAOKSXX_IN.setZHENGZHUANGDM("");
        requestGUAHAOKSXX_IN.setJIUZHENKH("");
        String request=XMLUtil.bean2xml(requestGUAHAOKSXX_IN);


        Map<String, String> map = new HashMap<String, String>();

        map.put("fid", "CY90004");
        map.put("deviceSign", "deviceSign");
        map.put("content", request);
        map.put("version", "5.0");
        map.put("ruleName", "CY90004");

        return  map;

    }
 

    public static class MyThread extends Thread{
		private String tradeType;
		private String tradeMessage;
		private Map<String, String> map;
		
		public MyThread(String tradeType,Map<String, String> map){
			this.tradeType = tradeType;
			this.map = map;
		}
		@Override
        public void run() {

			System.out.println("tradeType:" +tradeType+ "开始执行");
			System.out.println(map);
			long start = System.currentTimeMillis();
			
		try {
			 HttpClient client = getSecureConnection(); //使用ssl通信
		     //esb.z2yyservice.com
		     HttpUriRequest post = getRequestMethod(map, "https://183.129.242.246:19081/appserver-restful/requestMessage", "post");
		     HttpResponse response = client.execute(post);
		
		     if (response.getStatusLine().getStatusCode() == 200) {
		         HttpEntity entity = response.getEntity();
		         String message = EntityUtils.toString(entity, "utf-8");
		         System.out.println("消息大小" + message.length());
                 GUAHAOKSXX_OUT reponse = XMLUtil.xml2bean(GUAHAOKSXX_OUT.class, message);
		         //打印消息
		         System.out.println(message);
		     } else {
		         System.out.println("请求失败");
		     }    
		
//		 	client.getConnectionManager().shutdown();
				
			long end = System.currentTimeMillis();
			
			System.out.println("tradeType:" +tradeType + " ,线程消耗时间" +(end-start));
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	       

		}
	}
}
